package com.bzkj.web.controller.basic;

import com.bzkj.basicinfo.domain.CustomerMapping;
import com.bzkj.basicinfo.domain.vo.CustomerComparisonVo;
import com.bzkj.basicinfo.service.CustomerComparisonService;
import com.bzkj.basicinfo.service.CustomerMappingService;
import com.bzkj.common.core.controller.BaseController;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.page.PageDomain;
import com.bzkj.common.core.page.TableDataInfo;
import com.bzkj.common.core.page.TableSupport;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 往来单位对比控制器
 * 
 * @author system
 * @date 2025-01-29
 */
@Api(tags = "往来单位对比管理")
@RestController
@RequestMapping("/basic/customerComparison")
public class CustomerComparisonController extends BaseController {

    @Autowired
    private CustomerComparisonService customerComparisonService;

    @Autowired
    private CustomerMappingService customerMappingService;
    
    /**
     * 查询码上放心往来单位列表
     */
    @ApiOperation("查询码上放心往来单位列表")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:list')")
    @GetMapping("/msfxList")
    public TableDataInfo getMsfxCustomerList(
            @RequestParam(value = "customerName", required = false) String customerName,
            @RequestParam(value = "mappingStatus", required = false) Boolean mappingStatus) {
        // 获取分页参数
        PageDomain pageDomain = TableSupport.buildPageRequest();
        int pageNum = pageDomain.getPageNum();
        int pageSize = pageDomain.getPageSize();

        // 使用Service层的分页方法
        PageInfo<CustomerComparisonVo.MsfxCustomerVo> pageInfo = customerComparisonService.selectMsfxCustomerListWithPage(customerName, mappingStatus, pageNum, pageSize);

        // 构建返回结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(com.bzkj.common.constant.HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(pageInfo.getList());
        rspData.setTotal(pageInfo.getTotal());
        return rspData;
    }

    /**
     * 查询ERP往来单位列表
     */
    @ApiOperation("查询ERP往来单位列表")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:list')")
    @GetMapping("/erpList")
    public TableDataInfo getErpCustomerList(
            @RequestParam(value = "dwmch", required = false) String dwmch,
            @RequestParam(value = "mappingStatus", required = false) Boolean mappingStatus) {
        // 获取分页参数
        PageDomain pageDomain = TableSupport.buildPageRequest();
        int pageNum = pageDomain.getPageNum();
        int pageSize = pageDomain.getPageSize();

        // 使用Service层的分页方法
        PageInfo<CustomerComparisonVo.ErpCustomerVo> pageInfo = customerComparisonService.selectErpCustomerListWithPage(dwmch, mappingStatus, pageNum, pageSize);

        // 构建返回结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(com.bzkj.common.constant.HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(pageInfo.getList());
        rspData.setTotal(pageInfo.getTotal());
        return rspData;
    }

    /**
     * 查询往来单位对比数据
     */
    @ApiOperation("查询往来单位对比数据")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:list')")
    @GetMapping("/comparison")
    public AjaxResult getCustomerComparison(
            @RequestParam(value = "msfxCustomerName", required = false) String msfxCustomerName,
            @RequestParam(value = "erpCustomerName", required = false) String erpCustomerName,
            @RequestParam(value = "mappingStatus", required = false) Boolean mappingStatus) {
        CustomerComparisonVo result = customerComparisonService.selectCustomerComparison(msfxCustomerName, erpCustomerName, mappingStatus);
        return success(result);
    }

    /**
     * 查询映射关系列表
     */
    @ApiOperation("查询映射关系列表")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:list')")
    @GetMapping("/mappingList")
    public TableDataInfo getMappingList(CustomerMapping customerMapping) {
        startPage();
        List<CustomerMapping> list = customerMappingService.selectCustomerMappingList(customerMapping);
        return getDataTable(list);
    }

    /**
     * 获取映射关系详细信息
     */
    @ApiOperation("获取映射关系详细信息")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:query')")
    @GetMapping("/mapping/{id}")
    public AjaxResult getMappingInfo(@PathVariable("id") Long id) {
        return success(customerMappingService.selectCustomerMappingById(id));
    }

    /**
     * 创建映射关系
     */
    @ApiOperation("创建映射关系")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:add')")
    @PostMapping("/mapping")
    public AjaxResult createMapping(@RequestBody CustomerMapping customerMapping) {
        return customerMappingService.insertCustomerMapping(customerMapping);
    }

    /**
     * 快速创建映射关系
     */
    @ApiOperation("快速创建映射关系")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:add')")
    @PostMapping("/quickMapping")
    public AjaxResult quickCreateMapping(
            @RequestParam("msfxCustomerId") String msfxCustomerId,
            @RequestParam("msfxCustomerName") String msfxCustomerName,
            @RequestParam(value = "msfxEntId", required = false) String msfxEntId,
            @RequestParam("erpCustomerCode") String erpCustomerCode,
            @RequestParam("erpCustomerName") String erpCustomerName,
            @RequestParam(value = "erpDanwbh", required = false) String erpDanwbh,
            @RequestParam(value = "remark", required = false) String remark) {
        return customerMappingService.createMapping(msfxCustomerId, msfxCustomerName, msfxEntId,
                erpCustomerCode, erpCustomerName, erpDanwbh, remark);
    }

    /**
     * 批量创建映射关系（一个码上放心客户对应多个ERP客户）
     */
    @ApiOperation("批量创建映射关系")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:add')")
    @PostMapping("/batchMapping")
    public AjaxResult batchCreateMapping(@RequestBody BatchMappingRequest request) {
        return customerMappingService.createBatchMapping(
                request.getMsfxCustomerId(),
                request.getMsfxCustomerName(),
                request.getMsfxEntId(),
                request.getErpCustomerCodes(),
                request.getErpCustomerNames(),
                request.getErpDanwbhs(),
                request.getRemark());
    }

    /**
     * 批量映射请求DTO
     */
    public static class BatchMappingRequest {
        private String msfxCustomerId;
        private String msfxCustomerName;
        private String msfxEntId;
        private String[] erpCustomerCodes;
        private String[] erpCustomerNames;
        private String[] erpDanwbhs;
        private String remark;

        // Getters and Setters
        public String getMsfxCustomerId() { return msfxCustomerId; }
        public void setMsfxCustomerId(String msfxCustomerId) { this.msfxCustomerId = msfxCustomerId; }
        public String getMsfxCustomerName() { return msfxCustomerName; }
        public void setMsfxCustomerName(String msfxCustomerName) { this.msfxCustomerName = msfxCustomerName; }
        public String getMsfxEntId() { return msfxEntId; }
        public void setMsfxEntId(String msfxEntId) { this.msfxEntId = msfxEntId; }
        public String[] getErpCustomerCodes() { return erpCustomerCodes; }
        public void setErpCustomerCodes(String[] erpCustomerCodes) { this.erpCustomerCodes = erpCustomerCodes; }
        public String[] getErpCustomerNames() { return erpCustomerNames; }
        public void setErpCustomerNames(String[] erpCustomerNames) { this.erpCustomerNames = erpCustomerNames; }
        public String[] getErpDanwbhs() { return erpDanwbhs; }
        public void setErpDanwbhs(String[] erpDanwbhs) { this.erpDanwbhs = erpDanwbhs; }
        public String getRemark() { return remark; }
        public void setRemark(String remark) { this.remark = remark; }
    }

    /**
     * 修改映射关系
     */
    @ApiOperation("修改映射关系")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:edit')")
    @PutMapping("/mapping")
    public AjaxResult updateMapping(@RequestBody CustomerMapping customerMapping) {
        return customerMappingService.updateCustomerMapping(customerMapping);
    }

    /**
     * 删除映射关系
     */
    @ApiOperation("删除映射关系")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:remove')")
    @DeleteMapping("/mapping/{ids}")
    public AjaxResult removeMapping(@PathVariable Long[] ids) {
        return customerMappingService.deleteCustomerMappingByIds(ids);
    }

    /**
     * 审核映射关系
     */
    @ApiOperation("审核映射关系")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:audit')")
    @PostMapping("/mapping/audit")
    public AjaxResult auditMapping(
            @RequestParam("id") Long id,
            @RequestParam("auditStatus") Integer auditStatus,
            @RequestParam(value = "auditRemark", required = false) String auditRemark) {
        return customerMappingService.auditMapping(id, auditStatus, auditRemark);
    }

    /**
     * 解除映射关系
     */
    @ApiOperation("解除映射关系")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:remove')")
    @PostMapping("/mapping/remove/{mappingId}")
    public AjaxResult removeMapping(@PathVariable("mappingId") Long mappingId) {
        return customerMappingService.removeMapping(mappingId);
    }

    /**
     * 调试映射状态
     */
    @ApiOperation("调试映射状态")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:list')")
    @GetMapping("/debug/mapping/{erpDanwbh}")
    public AjaxResult debugMapping(@PathVariable("erpDanwbh") String erpDanwbh) {
        try {
            CustomerMapping mapping = customerMappingService.selectCustomerMappingList(new CustomerMapping() {{
                setErpCustomerCode(erpDanwbh);
            }}).stream().findFirst().orElse(null);

            if (mapping != null) {
                return AjaxResult.success("找到映射关系", mapping);
            } else {
                return AjaxResult.error("未找到映射关系，erpDanwbh: " + erpDanwbh);
            }
        } catch (Exception e) {
            return AjaxResult.error("调试失败: " + e.getMessage());
        }
    }

    /**
     * 查询未映射的码上放心往来单位
     */
    @ApiOperation("查询未映射的码上放心往来单位")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:list')")
    @GetMapping("/unmappedMsfx")
    public TableDataInfo getUnmappedMsfxCustomers(@RequestParam(value = "customerName", required = false) String customerName) {
        startPage();
        CustomerComparisonVo.MsfxCustomerVo[] list = customerComparisonService.selectUnmappedMsfxCustomers(customerName);
        return getDataTable(java.util.Arrays.asList(list));
    }

    /**
     * 查询未映射的ERP往来单位
     */
    @ApiOperation("查询未映射的ERP往来单位")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:list')")
    @GetMapping("/unmappedErp")
    public TableDataInfo getUnmappedErpCustomers(@RequestParam(value = "dwmch", required = false) String dwmch) {
        startPage();
        CustomerComparisonVo.ErpCustomerVo[] list = customerComparisonService.selectUnmappedErpCustomers(dwmch);
        return getDataTable(java.util.Arrays.asList(list));
    }

    /**
     * 查询启用状态的ERP往来单位列表
     */
    @ApiOperation("查询启用状态的ERP往来单位列表")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:list')")
    @GetMapping("/erpListEnabled")
    public TableDataInfo getEnabledErpCustomerList(
            @RequestParam(value = "dwmch", required = false) String dwmch,
            @RequestParam(value = "mappingStatus", required = false) Boolean mappingStatus) {
        CustomerComparisonVo.ErpCustomerVo[] list = customerComparisonService.selectEnabledErpCustomerList(dwmch, mappingStatus);
        return getDataTable(java.util.Arrays.asList(list));
    }

    /**
     * 预览自动匹配结果
     */
    @ApiOperation("预览基于名称完全匹配的自动映射结果")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:list')")
    @GetMapping("/autoMatchPreview")
    public AjaxResult previewAutoMatch() {
        return customerComparisonService.previewAutoMatch();
    }

    /**
     * 基于名称完全匹配自动创建映射关系
     */
    @ApiOperation("基于名称完全匹配自动创建映射关系")
    @PreAuthorize("@ss.hasPermi('basic:customerComparison:add')")
    @PostMapping("/autoMatch")
    public AjaxResult autoMatchByName() {
        return customerComparisonService.autoMatchByName();
    }

}
